package com.hks360.car_treasure.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.utils.CoordinateConverter;
import com.baidu.mapapi.utils.DistanceUtil;
import com.hks360.car_treasure.R;
import com.hks360.car_treasure.common.AppConfig;
import com.hks360.car_treasure.common.BaiduMapConfig;
import com.hks360.car_treasure.common.Method;
import com.hks360.car_treasure.common.PrefKey;
import com.hks360.car_treasure.fence.GeoFence;
import com.hks360.car_treasure.socket.CommunicationManager;
import com.hks360.car_treasure.socket.PhoneBandDevice;
import com.hks360.car_treasure.util.LogUtil;
import com.hks360.car_treasure.util.MyUtil;
import com.hks360.car_treasure.widget.ClickToogleButton;
import com.hks360.car_treasure.widget.FenceToogleButton;
import com.hks360.car_treasure.widget.ToogleButtonView;
import com.hks360.library.util.CommonUtil;
import com.hks360.library.util.PrefUtil;
import com.hks360.library.util.UIUtil;
import com.hks360.library.widget.CheckImageView;

import java.util.Arrays;
import java.util.List;

/**
 * Created by rwq on 2016/5/25.
 */
public class EfenceActivity extends BaseActivity {
    private MapView mFenceTmv;
    public static BaiduMap mBaiduMap;
    private LocationClient locClient;
    private float mZoomLevel;

    private SeekBar mSeekBar;
    private TextView num_tv;
    private int numbers = 0;
    private DisplayMetrics displaysMetrics;
    private double width, fDensity;

    private GeoFence mFence;
    private CheckImageView mFenceTypeCiv;
    private boolean FlagCiv = true;
    private LinearLayout mPop;
    private List<String> LLr;
    private ClickToogleButton mTb;
    private String describeStr;
    private ImageView mLocationChange;
    private boolean mFlag1 = false;
    private ImageView mAllDisplay;
    private boolean mFlag2 = false;

    private RelativeLayout mRlExample;
    private BaiduMap mExampleMap;
    private TextureMapView mExampleTmv;

    private FenceToogleButton mToogle1;
    private FenceToogleButton mToogle2;
    private FenceToogleButton mToogle3;
    private FenceToogleButton mToogle4;
    private FenceToogleButton mToogle5;
    private TextView mTv1;
    private TextView mTv2;
    private TextView mTv3;
    private TextView mTv4;
    private TextView mTv5;

    private final int LLR = 0;
    private final int A602 = 1;
    private final int B601 = 2;
    private final int GPS = 3;

    private boolean isSet = true;
    public static boolean isAlert = false;
    private boolean isGetLocation = false;
    private String alertDescript;
    private String latitude;
    private String longitude;
    private Double mLatitude;
    private Double mLongitude;
    private LatLng mll;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LLR:
                    try {
                        mFence.setCircle(new LatLng(Double.valueOf(LLr.get(1)), Double.valueOf(LLr.get(0))));
                        mFence.setRadius(Integer.valueOf(LLr.get(2)));
                        if (isAlert) {
                            mFence.setStyle(3);
                        } else {
                            mFence.setStyle(1);
                        }
                        mFence.createFence();
                        mSeekBar.setProgress(Integer.valueOf(LLr.get(2)) - 50);
                        //创建初始化围栏
                        initCurrentLocation();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case A602:
                    CommonUtil.showToast(EfenceActivity.this, describeStr);
                    CommonUtil.showToast(EfenceActivity.this, "已关闭电子围栏");
                    break;
                case B601:
                    isAlert = true;
                    CommonUtil.showToast(EfenceActivity.this, alertDescript);
                    mFence.setStyle(3);
                    mFence.createFence();
                    break;
                case GPS:
                    latitude = "";
                    longitude = "";
                    latitude = AppConfig.mComManager.G_BYTE(mGps,9)*1000000 + AppConfig.mComManager.G_BYTE(mGps,10)*10000 + AppConfig.mComManager.G_BYTE(mGps,11)*100 + AppConfig.mComManager.G_BYTE(mGps,12)+"";
                    longitude = AppConfig.mComManager.G_BYTE(mGps,13)*1000000 + AppConfig.mComManager.G_BYTE(mGps,14)*10000 + AppConfig.mComManager.G_BYTE(mGps,15)*100 + AppConfig.mComManager.G_BYTE(mGps,16) + "";
                    mLatitude = MyUtil.getBaiduLatitudeOrLongitude(latitude);
                    mLongitude = MyUtil.getBaiduLatitudeOrLongitude(longitude);
                    LatLng temp = new LatLng(mLatitude,mLongitude);
                    CoordinateConverter converter = new CoordinateConverter();
                    converter.from(CoordinateConverter.CoordType.GPS);
                    // sourceLatLng待转换坐标
                    converter.coord(temp);
                    temp = converter.convert();
                    mLatitude = temp.latitude;
                    mLongitude = temp.longitude;
                    isGetLocation = true;
                    break;
            }
        }
    };

    private void showLocation(double latitude, double longitude) {
        locClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(BaiduMapConfig.OPEN_GPS);// 打开gps
        option.setCoorType(BaiduMapConfig.COOR_TYPE); // 设置坐标类型
        option.setScanSpan(BaiduMapConfig.SCAN_SPAN);//设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);
        locClient.setLocOption(option);
        locClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (mll.latitude != 0 && mll.longitude != 0) {
                    try {
                        mBaiduMap.setMyLocationEnabled(true);
                        MyLocationData locData = new MyLocationData.Builder()
                                .accuracy(5)
                                // 此处设置开发者获取到的方向信息，顺时针0-360
                                .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(mll.latitude)
                                .longitude(mll.longitude).build();
                        mBaiduMap.setMyLocationData(locData);
                        locClient.stop();
                        initZoom(mll.latitude, mll.longitude);
                    } catch (Exception e) {
                    }
                } else {
                    try {
                        toCurrentLocation();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        locClient.start();
        mll = new LatLng(latitude, longitude);
    }

    private void initZoom(double latitude, double longitude) throws Exception {
        LatLng ll = new LatLng(latitude, longitude);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(ll).zoom(mZoomLevel);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    @Override
    public void initView() {
        AppConfig.mComManager.getCarInfo(PrefUtil.getString(this, PrefKey.TBOX_ID, ""));
        initData();
        initTitleBar("电子围栏");
        mZoomLevel = PrefUtil.getFloat(this, PrefKey.ZOOM, BaiduMapConfig.ZOOM_SUPERBIG);
        setupView();
        addListener();
    }


    public void addListener() {
        mAllDisplay.setOnClickListener(this);
        mLocationChange.setOnClickListener(this);
        mFenceTypeCiv.setOnClickListener(this);
        mTb.setOnToggleListener(new ClickToogleButton.OnToogleListener() {
            @Override
            public void onToogleChanged(boolean isOpen) {
                if (isOpen) {
                    mFence.setStyle(1);
                    mFence.createFence();
                    CommonUtil.showToast(EfenceActivity.this, "电子围栏已打开，请设置");
                } else {
                    AppConfig.mComManager.setEfence(mFence.getCircle().longitude + "", mFence.getCircle().latitude + "", "" + mFence.getRadius());
                    mFence.setStyle(2);
                    mFence.createFence();
                }
            }
        });
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (!isSet) {
                    mSeekBar.setProgress(0);
                    return;
                }
                if (!mTb.isOn()) {
                    mSeekBar.setProgress(0);
                } else {
                    LogUtil.e("System.out", progress + "");
                    mFence.setRadius(progress + 50);
                    mFence.setStyle(1);
                    mFence.createFence();
                }
                numbers = progress + 50;
                if (mTb.isOn()) {
                    //设置进度条下面数字的位置
                    setTextViewLocation(numbers);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (!mTb.isOn()) {
                    CommonUtil.showToast(EfenceActivity.this, "请先打开电子围栏");
                }
                if (!isSet) {
                    CommonUtil.showToast(EfenceActivity.this, "请先设置围栏中心点");
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mTb.isOn()) {
                    if (!isSet) {
                        mFence.setRadius(50);
                    }
                    mFence.setCircle(new LatLng(latLng.latitude, latLng.longitude));
                    mFence.createFence();
                    isSet = true;
                }
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        mToogle1.setOnToggleListener(new FenceToogleButton.OnToogleListener() {
            @Override
            public void onToogleChanged(boolean isOpen) {
                toCurrentLocation();
                MyLocationConfiguration.LocationMode currentModel = isOpen ? MyLocationConfiguration.LocationMode.COMPASS : MyLocationConfiguration
                        .LocationMode.NORMAL;
                mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(currentModel, true, null));
                mTv1.setText(isOpen ? "定位开" : "定位关");
            }
        });
        mToogle2.setOnToggleListener(new FenceToogleButton.OnToogleListener() {
            @Override
            public void onToogleChanged(boolean isOpen) {
                mBaiduMap.setBaiduHeatMapEnabled(isOpen);
                mTv2.setText(isOpen ? "热图开" : "热图关");
            }
        });
        mToogle3.setOnToggleListener(new FenceToogleButton.OnToogleListener() {
            @Override
            public void onToogleChanged(boolean isOpen) {
                if (isOpen) {
                    MapStatus ms = new MapStatus.Builder().overlook(-30).build();
                    MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms);
                    mBaiduMap.animateMapStatus(u);
                } else {
                    MapStatus ms = new MapStatus.Builder().overlook(0).build();
                    MapStatusUpdate u = MapStatusUpdateFactory.newMapStatus(ms);
                    mBaiduMap.animateMapStatus(u);
                }

                mTv3.setText(isOpen ? "俯视开" : "俯视关");
            }
        });
        mToogle4.setOnToggleListener(new FenceToogleButton.OnToogleListener() {
            @Override
            public void onToogleChanged(boolean isOpen) {
                mBaiduMap.setMapType(isOpen ? BaiduMap.MAP_TYPE_SATELLITE : BaiduMap.MAP_TYPE_NORMAL);
                mTv4.setText(isOpen ? "卫星开" : "卫星关");
            }
        });
        mToogle5.setOnToggleListener(new FenceToogleButton.OnToogleListener() {
            @Override
            public void onToogleChanged(boolean isOpen) {
                mBaiduMap.setTrafficEnabled(isOpen);
                mTv5.setText(isOpen ? "路况开" : "路况关");
            }
        });


    }

    @Override
    protected void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mFenceTmv.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mFenceTmv.onResume();
        super.onResume();
    }


    @Override
    public void viewClick(View v) {
        switch (v.getId()) {
            case R.id.fence_type_choose:
                mFenceTypeCiv.setChecked(FlagCiv);
                FlagCiv = !FlagCiv;
                if (FlagCiv) {
                    mPop.setVisibility(View.GONE);
                } else {
                    mPop.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.fence_location_change:
                mFlag1 = !mFlag1;
                if (mFlag1) {
                    if (isGetLocation) {
                        showLocation(mLatitude, mLongitude);
                    }
                } else {
                    mFence.createFence();
                }
                break;
            case R.id.fence_all_display:
                mFlag2 = !mFlag2;
                if (!isSet) {
                    CommonUtil.showToast(this, "未设置电子围栏,无法全局显示");
                    break;
                }
                mFence.createFence();
                if (mFlag2) {
                    mRlExample.setVisibility(View.VISIBLE);
                    mFenceTmv.showZoomControls(false);
                    mExampleTmv.showZoomControls(false);
                    mExampleMap = mExampleTmv.getMap();
                    // 开启定位图层
                    mExampleMap.setMyLocationEnabled(true);
                    // 定位初始化
                    final LocationClient mLocation = new LocationClient(this);
                    UiSettings mUiSettings = mExampleMap.getUiSettings();
                    BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.car_icon);
                    mExampleMap
                            .setMyLocationConfigeration(new MyLocationConfiguration(
                                    MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));
                    mUiSettings.setScrollGesturesEnabled(true);
                    if (!isGetLocation) {
                        toUserLocation(mLocation);
                    } else {
                        if (mLatitude != 0 && mLongitude != 0) {
                            MyLocationData locData = new MyLocationData.Builder()
                                    .accuracy(0)
                                    // 此处设置开发者获取到的方向信息，顺时针0-360
                                    .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(mLatitude)
                                    .longitude(mLongitude).build();
                            mExampleMap.setMyLocationData(locData);
                            LatLng ll = new LatLng(mLatitude, mLongitude);
                            MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(ll, 15);
                            mExampleMap.animateMapStatus(mapStatus);
                        } else {
                            toUserLocation(mLocation);
                        }

                    }
                } else {
                    mRlExample.setVisibility(View.INVISIBLE);
                }
                break;
        }
    }

    private void toUserLocation(final LocationClient mLocation) {
        if (mLocation != null) {
            mLocation.stop();
        }
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);                                //打开gps
        option.setCoorType("bd09ll");                           //设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置网络优先
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);                               //定时定位，每隔5秒钟定位一次。
        mLocation.setLocOption(option);
        mLocation.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation == null || mExampleTmv == null) {
                    return;
                }
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(0)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude()).build();
                mExampleMap.setMyLocationData(locData);
                LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(ll, mZoomLevel);
                mExampleMap.animateMapStatus(mapStatus);
                mLocation.stop();
            }
        });
        mLocation.start();
    }

    public void setupView() {
        mFence = new GeoFence();
        mFenceTmv = UIUtil.findViewById(this, R.id.fence_tmv);
        mRlExample = UIUtil.findViewById(this, R.id.rl_example_map);
        mExampleTmv = UIUtil.findViewById(this, R.id.expample_map);
        mSeekBar = UIUtil.findViewById(this, R.id.efence_seekBar);
        mAllDisplay = UIUtil.findViewById(this, R.id.fence_all_display);
        mFenceTypeCiv = UIUtil.findViewById(this, R.id.fence_type_choose);
        mLocationChange = UIUtil.findViewById(this, R.id.fence_location_change);

        mToogle1 = UIUtil.findViewById(this, R.id.toogle1);
        mToogle2 = UIUtil.findViewById(this, R.id.toogle2);
        mToogle3 = UIUtil.findViewById(this, R.id.toogle3);
        mToogle4 = UIUtil.findViewById(this, R.id.toogle4);
        mToogle5 = UIUtil.findViewById(this, R.id.toogle5);

        mTv1 = UIUtil.findViewById(this, R.id.bt_tv1);
        mTv2 = UIUtil.findViewById(this, R.id.bt_tv2);
        mTv3 = UIUtil.findViewById(this, R.id.bt_tv3);
        mTv4 = UIUtil.findViewById(this, R.id.bt_tv4);
        mTv5 = UIUtil.findViewById(this, R.id.bt_tv5);

        num_tv = UIUtil.findViewById(this, R.id.num_tv);

        mPop = UIUtil.findViewById(this, R.id.popup);
        mSeekBar.setMax(10000 - 50);
        mBaiduMap = mFenceTmv.getMap();
        mUiSettings = mBaiduMap.getUiSettings();
        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.car_icon);
        mBaiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL, true, mCurrentMarker));
        mUiSettings.setScrollGesturesEnabled(true);
    }

    private BitmapDescriptor mCurrentMarker;
    private UiSettings mUiSettings;
    private byte[] mGps;

    @Override
    public void initData() {
        AppConfig.mComManager.getEfence();
        AppConfig.mComManager.setOnRecvCommunicationListener(new CommunicationManager.OnRecvCommunicationListener() {
            @Override
            public void onRecv_B001(int answerID, byte[] message) {
                switch (answerID) {
                    case 0xA602:
                        describeStr = CommunicationManager.getCmdString(message, 18);
                        handler.sendEmptyMessage(A602);
                        break;
                }

            }

            @Override
            public void onRecv_B601(String description) {
                alertDescript = description;
                handler.sendEmptyMessage(B601);
            }

            @Override
            public void onRecv_A602(List<String> llr) {
                if (llr.size() != 0) {
                    LLr = llr;
                    Log.e("rwq", "longitude==>" + llr.get(0) + "latidude==>" + llr.get(1)
                            + "radius==>" + llr.get(2));
                    handler.sendEmptyMessage(LLR);
                }
            }

            @Override
            public void onRecv_B500(byte[] message) {

            }

            @Override
            public void onRecv_B208(List<PhoneBandDevice> itemsDevices) {

            }

            @Override
            public void onRecv_CarStatus(byte[] carStatusBytes) {

            }

            @Override
            public void onRecv_Gps(byte[] gpsBytes) {
                mGps = gpsBytes;
                Log.e("RWQ", Arrays.toString(mGps));
                handler.sendEmptyMessage(GPS);
            }

            @Override
            public void onConnectBreak() {

            }

            @Override
            public void onRecv_B208Error() {

            }
        });
    }


    private void initCurrentLocation() throws Exception {
        if (Double.valueOf(LLr.get(0)) == 0 && Double.valueOf(LLr.get(1)) == 0 || Double.valueOf(LLr.get(2)) == 0) {
            CommonUtil.showToast(this, "未设置电子围栏");
            if (isGetLocation) {
                showLocation(mLatitude, mLongitude);
            } else {
                AppConfig.mComManager.getCarInfo(PrefUtil.getString(this, PrefKey.TBOX_ID, ""));
            }
            num_tv.setVisibility(View.INVISIBLE);
            isSet = false;
        } else {
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
            LatLng ll = new LatLng(Double.valueOf(LLr.get(0)), Double.valueOf(LLr.get(1)));
            try {
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(0)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(ll.latitude)
                        .longitude(ll.longitude).build();
                mBaiduMap.setMyLocationData(locData);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mBaiduMap.setMyLocationEnabled(false);
        }

    }

    private LatLng currentLL;

    private void toCurrentLocation() {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        if (locClient != null) {
            locClient.stop();
        }
        locClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);                                //打开gps
        option.setCoorType("bd09ll");                           //设置坐标类型为bd09ll
        option.setPriority(LocationClientOption.NetWorkFirst);  //设置网络优先
        option.setProdName("locSDKDemo2");                      //设置产品线名称
        option.setScanSpan(5000);                               //定时定位，每隔5秒钟定位一次。
        locClient.setLocOption(option);
        locClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (bdLocation == null || mFenceTmv == null) {
                    return;
                }
                LogUtil.d(bdLocation.getLatitude() + "," + bdLocation.getLongitude());
                // map view 销毁后不在处理新接收的位置
                LatLng ll;
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(0)
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(BaiduMapConfig.MAP_ROTATE_DEFAULT).latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());
                currentLL = ll;
                MapStatus.Builder builder = new MapStatus.Builder();
                try {
                    builder.target(ll).zoom(mZoomLevel);
                    MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(ll, mZoomLevel);
                    mBaiduMap.animateMapStatus(mapStatus);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                locClient.stop();

            }
        });
        locClient.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.efence_activity);
        initView();
        initSeekBarProgress();
    }

    //TextView跟随SeekBar移动
    private void initSeekBarProgress() {
        displaysMetrics = getResources().getDisplayMetrics();
        width = displaysMetrics.widthPixels;
        fDensity = (width - dip2px(this, 51)) / 10000;
        mSeekBar.setProgress(numbers);
        setTextViewLocation(numbers + 50);
    }

    private void setTextViewLocation(int num) {
        if (numbers < 5000) {
            RelativeLayout.LayoutParams paramsStrength = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            paramsStrength.leftMargin = (int) (numbers * fDensity) + dip2px(EfenceActivity.this, 45);
            paramsStrength.addRule(RelativeLayout.CENTER_VERTICAL);
            num_tv.setLayoutParams(paramsStrength);
            num_tv.setText(num + "m");
        } else {
            RelativeLayout.LayoutParams paramsStrength = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            paramsStrength.leftMargin = (int) (numbers * fDensity) - dip2px(EfenceActivity.this, 35);
            paramsStrength.addRule(RelativeLayout.CENTER_VERTICAL);
            num_tv.setLayoutParams(paramsStrength);
            num_tv.setText(num + "m");
        }
    }

    /**
     * 根据手机分辨率从 dp 单位 转成 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFenceTmv.onDestroy();
        PrefUtil.putFloat(this, PrefKey.ZOOM, 18);
    }


    @Override
    public void initTitleBar(String txtResId) {
        super.initTitleBar(txtResId);
        mTb = UIUtil.findViewById(this, R.id.toggleButton);
        mTb.setVisibility(View.VISIBLE);
        ImageView mIv = UIUtil.findViewById(this, R.id.left_iv);
        mIv.setVisibility(View.INVISIBLE);

    }
}
